#!/usr/bin/python
# -*- coding: utf-8 -*-
import os,sys
import urllib,urllib2
from datetime import datetime
from wsgiref.handlers import format_date_time
import calendar

from ntlm import HTTPNtlmAuthHandler
from win32com.client import Dispatch

NAME = "邵峰"
user = 'NTDOMAIN\shaof'
password = ""
url_part1 = "http://sharepoint2008/Shared%20Documents/%E5%91%98%E5%B7%A5%E5%B7%A5%E4%BD%9C%E6%97%B6%E9%97%B4/"
url_part2 = "%20%E4%B8%8A%E7%8F%AD%E6%89%93%E5%8D%A1%E8%AE%B0%E5%BD%95.xls"
tmp_folder = "tmp"
if not os.path.exists(tmp_folder):
    tmp_folder = "tmp"
if not os.path.exists(tmp_folder):
    os.mkdir(tmp_folder)
tmp_folder = os.path.abspath(tmp_folder)

excel = Dispatch('Excel.Application')
excel.Visible = 0

def download_file(date, fn):
    headers = {}
    if os.path.exists(fn) and os.stat(fn).st_size > 1024:
        print "file exists, check for modification"
        headers["If-Modified-Since"] = format_date_time(os.stat(fn).st_mtime)
    
    passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
    passman.add_password(None, url_part1, user, password)
    # create the NTLM authentication handler
    auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)
    
    # create and install the opener
    opener = urllib2.build_opener(auth_NTLM)
    urllib2.install_opener(opener)
    
    # retrieve the result
    downloadurl = url_part1 + date + url_part2
    req = urllib2.Request(downloadurl, None, headers)
    response = urllib2.urlopen(req)
    if response.fp.status == 200:
        open(fn,'wb').write(response.read())
    elif response.fp.status == 304:
        print "cache hit"
    else:
        raise urllib2.HTTPError(downloadurl, response.fp.status, response.fp.reason, response.fp.getheaders, response.fp.fp)

def get_time_of_day(date):
    fn = os.path.join(tmp_folder, date+".xls")
    try:
        print "getting %s"%date
        download_file(date, fn)
    except urllib2.HTTPError,e:
        if e.code == 404:
            print "file not found in server"
            return None
        raise e
    book = excel.Workbooks.Open(fn)
    try:
        row = 1
        while True:
            name = book.Sheets[0].Cells(row, 1).Value
            if not name:
                return None
            name = name.encode('utf8').strip()
            if len(name) == 0:
                return None
            if name == NAME:
                return book.Sheets[0].Cells(row, 4).Value.encode('utf8')
            row += 1
    finally:
        book.Close()

def get_time_of_month(month):
    l = list()
    for d in xrange(1,calendar.monthrange(*map(int,month.split('-')))[1]+1):
        day = month+"-%02d"%d
        if datetime.strptime(day, "%Y-%m-%d").weekday() < 5:
            l.append((day, get_time_of_day(day)))
    return l

def main():
    global password,url_part1
    if len(sys.argv) > 1:
        month = sys.argv[1]
    else:
        month = raw_input("input month(YYYY-MM): ")
    if not password:
        password = raw_input("password for %s: " % urllib.splithost(urllib.splittype(url_part1)[1])[0])
    l = get_time_of_month(month)
    rl = []
    for d in l:
        if d[1] != None:
            t = datetime.strptime(d[1], '%Y-%m-%d %H:%M:%S')
            if t.strftime("%H:%M:%S") > "08:30:00":
                rl.append(t)
    print "here is result:"
    print "----------------------------"
    print '\n'.join(
        t.strftime("%Y-%m-%d %H:%M:%S")
        for t in rl
        )
    print "----------------------------"
    print "total %d day(s)" % len(rl)
    raw_input()
    return 0

if __name__ == '__main__':
    sys.exit(main())

